package com.doupi.partner.util;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Constructor;

/**
 * 断言工具
 * 
 * @author Alvin Wang
 * @version 1.0.0 @ 2017-04-19
 */
public class AssertUtils {

	public static void assertNotNull(Object obj, String message) {
		if (null == obj) {
			throw RuntimeBusinessException.createException(message);
		}
	}

	public static void assertNull(Object obj, String message) {
		if (null != obj) {
			throw RuntimeBusinessException.createException(message);
		}
	}

	public static void isTrue(boolean value, String message) {
		if (!value) {
			throw RuntimeBusinessException.createException(message);
		}
	}

	public static void assertNotBlank(String string, String message) {
		if (StringUtils.isBlank(string)) {
			throw RuntimeBusinessException.createException(message);
		}
	}

	public static void assertNotNull(Object obj, String message, Class<? extends Exception> exceptionClass) {
		if (null == obj) {
			try {
				Constructor<? extends Exception> constructor = exceptionClass.getConstructor(String.class);
				throw constructor.newInstance(message);
			} catch (Exception e) {
				// should not appear
				throw new RuntimeException(e);
			}
		}
	}

	/**
	 * 断言非空
	 *
	 * @param object
	 *            断言对象
	 * @param code
	 *            异常code
	 * @param message
	 *            异常消息
	 */
	public static void assertNotNull(Object object, String code, String message) {
		if (null == object) {
			throw RuntimeBusinessException.createException(code, message);
		}
	}

	/**
	 * 断言相等
	 *
	 * @param expected
	 *            期望值
	 * @param actual
	 *            实际值
	 * @param code
	 *            异常code
	 * @param message
	 *            异常消息
	 */
	public static void assertEqual(Object expected, Object actual, String code, String message) {
		if (!isEqual(expected, actual)) {
			throw RuntimeBusinessException.createException(code, message);
		}
	}

	/**
	 * 判断是否相等
	 *
	 * expected is null, actual not then return false
	 *
	 * otherwise return expected.equals(actual)
	 *
	 * @param expected
	 *            期望值
	 * @param actual
	 *            实际值
	 * @return expected equal actual true otherwise false
	 *
	 */
	private static boolean isEqual(Object expected, Object actual) {
		return null == expected ? null == actual : expected.equals(actual);
	}
}
